﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using EmptyWallGallery.Core;
using EmptyWallGallery.Core.Utilities;

namespace EmptyWallGallery.FrontEnd.inside.Editor.Articles
{
    public partial class Create : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            catdetail.InnerHtml = Core.BLL.Categories.Instance.WriteCategoryInside(3, 1);
            ArticlePublishContent.InnerHtml = WriteScheduleDate();

            Page.Title = "Thêm mới tin bài - " + Configs.WebTitle;
        }

        protected void BtnCreateClick(object sender, EventArgs e)
        {
            if (txtTitle.Text == null)
            {
                txtTitle.Text = "No Title";
            }
            else if (txtTitle.Text.Length > 550)
            {
                txtTitle.Text = Server.HtmlEncode(txtTitle.Text.Trim().Substring(0,500));
            }

            var strTitle = Common.Instance.NoHtml(Server.HtmlEncode(txtTitle.Text.Trim()));
            var titleNone = Common.Instance.Utf8ToAscii(Server.HtmlDecode(strTitle));
            var strBody = txtBody.Value;
            var strAbstract = Common.Instance.NoHtml(Server.HtmlEncode(txtDesc.Text.Trim()));
            var createdDate = DateTime.Now;
            var releaseDate = DateTime.Now;
            string imagePath;
            var strCatTemp = "";

            if (fileUpload.HasFile)
            {
                var randomStr = new RandomStrings();
                var strFileName = randomStr.GenerateRandomString(DateTime.Now) + ".jpg";
                var strFolder = string.Format("{0}{1}\\{2}\\{3}\\{4}\\", Configs.UserFolder,
                              HttpContext.Current.User.Identity.Name, DateTime.Now.Year,
                              Common.Instance.Right("0" + DateTime.Now.Month, 2),
                              Common.Instance.Right("0" + DateTime.Now.Day, 2));

                if (!Directory.Exists(strFolder))
                {
                    Directory.CreateDirectory(strFolder);
                }

                var objImage = new ImageUtil(fileUpload.PostedFile.InputStream, 1024, 1024, "UploadService", "admin",
                                             strFileName, 100);
                objImage.PublicUpload(300, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(202, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(145, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(100, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(42, 0, strFileName, 100, "", strFolder);

                imagePath = strFolder.Replace(Configs.UserFolder, "").Replace("\\", "/") + "100x0__" + strFileName;
            }
            else
            {
                imagePath = "";
            }

            //Create Article
            var membershipUser = Membership.GetUser();
            if (membershipUser == null) return;
            if (membershipUser.ProviderUserKey == null) return;

            var articleItem = Core.BLL.Articles.Instance.CreateProduct(strTitle, strAbstract, releaseDate, imagePath, titleNone, "", 
                                                                        createdDate, membershipUser.ProviderUserKey.ToString(), 0);
            var strId = articleItem.ArticlesId;
            
            //Create Article Category
            if (Request.Form.Get("cboCategory") == null)
            {
                Core.BLL.Articles.Instance.SetTempArticleCat(0, 1, strId);
            }
            else
            {
                foreach (var strCatId in Regex.Split(Request.Form["cboCategory"], ","))
                {
                    strCatTemp = strCatId;

                    var str = strCatTemp.Split(new[] { '|' });
                    Core.BLL.Articles.Instance.SetTempArticleCat(0, int.Parse(str[0]), strId);
                }
            }

            articleItem.ArticlePath = "/" + createdDate.Year + "/" + Common.Instance.Right("0" + createdDate.Month, 2) +
                                      "/" + Common.Instance.Right("0" + createdDate.Day, 2) + "/" + titleNone + "-" +
                                      Common.Instance.HexValue(strId);

            Core.BLL.Articles.Instance.UpdateArticlePath(articleItem.ArticlePath, strId);
            Core.BLL.Articles.Instance.WriteXmlbyId(articleItem, strBody, strCatTemp);

            Response.Redirect("ArticleUpdate.aspx?ID=" + strId + "&MsgID=6");
        }

        public string WriteScheduleDate()
        {
            var strOut = new StringBuilder();
            strOut.Append(
                "<br /><select name=\"mmmm\" id=\"mmmm\"><option value=\"1\">Jan</option><option value=\"2\">Feb</option><option value=\"3\">Mar</option><option value=\"4\">Apr</option><option value=\"5\">May</option><option value=\"6\">Jun</option><option value=\"7\">Jul</option><option value=\"8\">Aug</option><option value=\"9\">Sep</option><option value=\"10\">Oct</option><option value=\"11\">Nov</option><option value=\"12\">Dec</option></select> ");
            strOut.Append("<input type=\"text\" style=\"width:auto;\" id=\"dd\" name=\"dd\" value=\"").Append(
                DateTime.Now.Day).Append("\" size=\"2\" maxlength=\"2\" autocomplete=\"off\" />");
            strOut.Append(", <input type=\"text\" style=\"width:auto;\" id=\"yy\" name=\"yy\" value=\"").Append(
                DateTime.Now.Year).Append(
                    "\" size=\"4\" maxlength=\"4\" tabindex=\"4\" autocomplete=\"off\" /> @ <input style=\"width:auto;\" type=\"text\" id=\"hh\" name=\"hh\" value=\"")
                .Append(DateTime.Now.Hour).Append(
                    "\" size=\"2\" maxlength=\"2\" tabindex=\"4\" autocomplete=\"off\" /> : <input style=\"width:auto;\" type=\"text\" id=\"mn\" name=\"mn\" value=\"")
                .Append(DateTime.Now.Minute).Append(
                    "\" size=\"2\" maxlength=\"2\" tabindex=\"4\" autocomplete=\"off\" /><input type=\"hidden\" id=\"ss\" name=\"ss\" value=\"")
                .Append(DateTime.Now.Second).Append("\" />");
            strOut.Append(
                "<input type=\"button\" value=\"OK\" class=\"button\" onclick=\"javascript:Util.PublishConfirmAction();\" /> ");
            strOut.Append(
                "<a onclick=\"javascript:Util.CancelArticlePublish();\" title=\"Cancel\" href=\"#\">Cancel</a><input type=\"hidden\" id=\"txtReleaseDate\" name=\"txtReleaseDate\" />");
            strOut.Append("<script type=\"text/javascript\" language=\"javascript\">gmobj(\"mmmm\").value = ").Append(
                DateTime.Now.Month).Append(";</script>");
            return strOut.ToString();
        }
    }
}